<?php
    require_once('../lib/JSSDK.php');
    $jssdk = new JSSDK("wx4aed25d0aeefc592","6368d8bf66542dd5d0d3e9cfbd50be37");
    $signPackage = $jssdk->getSignPackage();
?>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CHIC原醉</title>
    <link rel="stylesheet" href="/css/index.css">
    <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <script type="text/javascript" src="/js/swfobject.js"></script>
    <script type="text/javascript" src="/js/web_socket.js"></script>
    <script type="text/javascript" src="/js/jquery.min.js"></script>

    <script type="text/javascript">
        wx.config({
            debug: false, 
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onVoiceRecordEnd',
            'playVoice',
            'onVoicePlayEnd',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard'
            ]
        });

    </script>
<script type="text/javascript">
<?php
    $time = time();
?>
ROOM_ID = "<?php echo base64_encode("0577:1818:".$time)?>";
USER_ICON = "/img/chat-img.png";
USER_ID = "<?php echo $_GET['uid']?>";
USER_TYPE = '<?php echo $_GET['utype']?>';
USER_SEND = "<?php echo $_GET['usend']?>"
WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
WEB_SOCKET_DEBUG = true;
var ws;
function connect() {
    ws = new WebSocket("ws://"+document.domain+":7272");
    ws.onopen = onopen;
    ws.onmessage = onmessage; 
    ws.onclose = function() {
        connect();
    };
    ws.onerror = function() {
    };
}
function onopen() {
    var login_data = '{"type":"login","user_type":"'+USER_TYPE+'","user_id":"'+USER_ID+'","icon":"'+USER_ICON+'","room_id":"'+ROOM_ID+'"}';
    ws.send(login_data);
}
function onmessage(e) {
    var data = eval("("+e.data+")");
    console.log(data);
    switch(data['type']){
        case 'ping':
            ws.send('{"type":"pong"}');
            break;;
        case 'login':
            break;
        case 'say':
            retMsg(data['type'], data['user_id'], data['icon'], data['content']);
            break;
        case 'audio':
            retMsg(data['type'], data['user_id'], data['icon'], data['content']);
            break;
        case 'logout':
	    console.log(data);
            if(data['user_id'] == USER_ID){
		ws.onclose = function(){};
		ws.close();
                alert("你"+data['content']);
	    }else{
		alert("ta"+data['content']);
            }
            break;
    }
}
function retMsg(type, user_id, icon, content){
    if(user_id == USER_ID)
        p = '.myself';
    else
        p = '.themself'

    if (type == 'say') {
        p += '-chat-text';
    }else{
        p += '-chat-audio';
    }
    var html = $(p).html().replace('{{icon}}',icon).replace('{{content}}',content);
    if(localStorage.length > 0){
        var db = localStorage.getItem('chat-db');
        db = JSON.parse(db);
	if(db.length >= 5){
	    db.shift();
	}
	db.push(html);
        localStorage.setItem('chat-db',JSON.stringify(db));
    }else{
	db = new Array();
	db.push(html);
        localStorage.setItem('chat-db',JSON.stringify(db));
    }
    $(".chat").append(html);
}
function send(content){
    var sendMsg = {
        'type':USER_SEND,
        'user_id':USER_ID,
        'icon':USER_ICON,
        'user_type':USER_TYPE,
        'content': content,
    };
    ws.send(JSON.stringify(sendMsg));
}
</script>
</head>
<script type="text/template" class="myself-chat-text">
    <div class="chat-right chat-item">
        <img src="{{icon}}" alt="" class="chat-img">
        <div class="chat-text">{{content}}</div>
    </div>
</script>
<script type="text/template" class="myself-chat-audio">
    <div class="chat-right chat-item">
        <img src="{{icon}}" alt="" class="chat-img">
        <div class="chat-text" onclick="play('{{content}}')">语音</div>
    </div>
</script>

<script type="text/template" class="themself-chat-text">
    <div class="chat-left chat-item">
        <img src="{{icon}}" alt="" class="chat-img">
        <div class="chat-text">{{content}}</div>
    </div>
</script>
<script type="text/template" class="themself-chat-audio">
    <div class="chat-left chat-item">
        <img src="{{icon}}" alt="" class="chat-img">
        <div class="chat-text" onclick="play('{{content}}')">语音</div>
    </div>
</script>
<body class="pt54 pb60" onload="connect()">

    <div class="top-menu">
        <a href="" class="logo"></a>
        <div class="top-menu-right">
            <span class="search-btn"></span>
            <div class="bread-menu-btn"><i></i><i></i><i></i></div>
        </div>
        <div class="bread-menu-panel pt54">
            <a href="">首页</a>
            <a href="">我的</a>
        </div>
    </div>

    <div class="container">
        <div class="chat">
        </div>
        <span class="countdown">59:45</span>
        <div class="chat-bottom">

        <?php if ($_GET['usend']=='say') {?>
            <div class="chat-input">
                <input type="text" id="input-content" placeholder="输入您想咨询的内容的...">
            </div>
        <?php } ?>

        <?php if ($_GET['usend']=='audio') {?>
            <div class="btn-audio voiceBox">按住说话</div>
        <?php } ?>
        </div>
        <div class="audio-animate" style="display: none;">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </div>
    </div>

    <script>
      $(function () {
        $('.bread-menu-btn').on('click', function () {
          $(this).toggleClass('active');
          $('.top-menu').toggleClass('active');
          $('.bread-menu-panel').toggleClass('active');
        });
	if(localStorage.length > 0){
		var chat_db = localStorage.getItem('chat-db');
		chat_db = JSON.parse(chat_db);
		$.each(chat_db,function(i){
		    $(".chat").append(chat_db[i]);
		});
	}

        /*
            text
        */
        <?php if ($_GET['usend']=='say') {?>
            $('#input-content').keydown(function(e){
                if(e.keyCode == 13){
                    send($('#input-content').val());
                    $('#input-content').val('');
                }
            });
        <?php } ?>
        /*
            audio
        */
      })
    </script>
    <script type="text/javascript">
        function secondToDate(result) {
            var m = Math.floor((result / 60));
            var s = Math.floor((result % 60));
            return m+":"+s;
        }
        var timer = 60;
        $(function (){
            var timerun = setInterval(function(){
		if(timer > 0){
                	$('.countdown').html(secondToDate(--timer));
		}else{
			clearInterval(timerun);
		}
            },1000);
        });
        function play(localId){
            console.log('play1');
            wx.downloadVoice({
                serverId: localId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    console.log(res.localId);
                    wx.playVoice({
                        localId: res.localId
                    });
                }
            });
        }
        $btn = ".voiceBox";
        voice = {
            localId:''
        };
        wx.ready(function (){
        });

        $(function(){
            $($btn).on('touchstart',function(event){
                event.preventDefault();
                START = new Date().getTime();
                recordTimer = setTimeout(function(){
                    wx.startRecord({
                        success:function(){
                            localStorage.rainAllowRecord = 'true';
                            $('.audio-animate').css('display','block');
                        },
                        cancel:function(){
                            alert("拒绝授权录音");
                            $('.audio-animate').css('display','none');
                        }
                    });
                },300);
            });
            $($btn).on('touchend',function(event){

                event.preventDefault();
                END = new Date().getTime();

                if((END-START)<300){
                    END = 0;
                    START = 0;
                    clearTimeout(recordTimer);
                    $('.audio-animate').css('display','none');
                }else{
                    wx.stopRecord({
                        success:function(res){
                            voice.localId = res.localId;
                            wx.playVoice({
                                localId: res.localId
                            });
                            uploadVoice();
                            $('.audio-animate').css('display','none');
                        },
                        fail:function(res){
                            $('.audio-animate').css('display','none');
                            alert(JSON.stringify(res));
                        }
                    });
                }

            });
        });
        function uploadVoice(){
            //调用微信的上传录音接口把本地录音先上传到微信的服务器
            //不过，微信只保留3天，而我们需要长期保存，我们需要把资源从微信服务器下载到自己的服务器
            wx.uploadVoice({
                localId: voice.localId, // 需要上传的音频的本地ID，由stopRecord接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    send(res.serverId);
                }
            });
        }
    </script>
</body>
</html>
